<template>
  <div>
    <div style="display:flex;align-items:center;justify-content:space-between;margin-top:.75rem;border:none;">
      <div style="display:flex;align-items:center;">
        <img src="~/static/guangchang/left@2x(1).png" alt="" style="width:3.5rem;height:2.75rem;object-fit:contain;"
          @click="goBack">
        <div style="font-weight:bold;font-size:1rem">{{lunts[fabutypes]}}</div>
      </div>
      <!-- <img v-if="dongtai.title=='1'" src="~/static/guangchang/fabucheng1.png" alt=""
        style="width:5.5rem;height:2.75rem;object-fit:contain;"> -->
      <!-- <img v-else src="~/static/guangchang/fabucheng.png" alt="" style="width:5.5rem;height:2.75rem;object-fit:contain;"
        @click="favus()"> -->
    </div>
    <div style="display:flex;align-items:center;">
      <div style="width:2.25rem;margin:0 .625rem"></div>
      <div style="width:100%">
        <div style="margin-top:.625rem;width:100%">
          <div id="editor" style=" border: none; padding:0;max-width:43.75rem;text-wrap:wrap;max-height:15.5rem"></div>
        </div>
      </div>
    </div>
    <div style="display:flex;align-items:center;margin-top:.625rem;">
      <div style="width:2.25rem;margin:0 .625rem"></div>
      <div style="display:flex;align-items:center;position:relative;">
        <img v-if="fabutypes==0" src="~/static/guangchang/youxi.png" alt=""
          style="width:3.75rem;height:1.5625rem;object-fit:contain;" @click="youxiTopicList('segame')">
              <div v-if="showTopicList" class="topic-list">
      <div v-for="(topic, index) in topics" :key="index"
        :class="['topic-item', topic.type === 'game' ? 'topic-color-game' : (topic.type === 'subject' ? 'topic-color-subject' : '')]"
        @click="insertTopic(topic)">
        <div style="display:flex;align-items:baseline;">
            <img v-if="topic.type === 'game'" src="http://beta.tool.77.top/static/test.png" alt="" style="width:12px;height:12px;object-fit:contain;margin-right:4px;     transform: translateY(2px);
">
             <div >
               <div style="color: #2E3033;font-size: 12px;">{{ topic.name }}</div>
                    <div style="font-size: 10px;color: #959699;margin-top: 4px">{{ topic.number }}</div>
             </div>
            
        </div>
   
      </div>
    </div>
        <!-- <img v-if="fabutypes==0" src="~/static/guangchang/huati.png" alt=""
          style="width:3.75rem;height:1.5625rem;object-fit:contain;margin:0 12px" @click="youxiTopicList('sesubject')"> -->
        <input type="file" id="fileInput" multiple accept="image/*" style="display:none" @change="handleFileChange">
        <img src="~/static/guangchang/tupian.png" alt="" style="width:3.75rem;height:1.5625rem;object-fit:contain;"
          @click="triggerFileInput">
      </div>
    </div>
    <div class="image-gallery">
      <div v-for="(image, index) in selectedarray" :key="index" style="position:relative;">
        <img :src="image" 
           :alt="'Image ' + (index + 1)"
      :style="getImageStyle(selectedarray.length)"
      :class="getImageClass(index, selectedarray.length)">
        <img src="~/static/guangchang/quxiaos.png" alt=""
          style="position:absolute;top:0;right:0;width:2rem;height:2rem;object-fit:contain;cursor:pointer;"
          @click.stop="removeImage(index)">
      </div>
    </div>
    <div style="display:flex;align-items:center;justify-content:center;width:100%; position: fixed;
  bottom: 20px;
  left: 0;" @click="fabus()"> <div  class="fabuquanzi">{{lunts[fabutypes]}}</div></div>
   
  </div>
</template>

<script>
import md5 from 'js-md5';

export default {
  data() {
    return {
      editor: null,
      showTopicList: false,
      topics: [],
      selectedImages: '',
      uid: "",
      t: '',
      textToHash: '',
      selectedarray: [],
      dongtai: {
        title: '',
        content: '',
        images: [],
        subject_id: '',
        gid: '',
      },
      fabutypes: 0,
      lunts: {
        0: '发布到圈子',
        1: '发布到论坛',
        2: '发布到话题'
      },
    }
  },
  mounted() {
    this.fabutypes = this.$route.query.e
    this.uid = this.getCookie('loginnew');
    this.t = Date.now();
    const sign = `${this.uid}${this.t}fsd213ewdsadqwe2121213edsad`;
    this.textToHash = md5(sign);
    this.editor = new Quill('#editor', {
      theme: 'snow',
      placeholder: '在此处输入内容...',
      modules: {
        toolbar: false
      }
    });
    this.editor.on('text-change',this.handleEditorChange.bind(this));
  },
  methods: {
     async fabus() {
      if(this.uid == null || this.uid == undefined || this.uid == ''){
        window.location.href = `${this.$domain}/?ct=wap&ac=login&goto=https:m.77.top/fabu?e=0`;
      }
      const delta = this.editor.getContents();
      let textContent = '';

      delta.ops.forEach(op => {
        if (op.insert) {
          if (typeof op.insert === 'string') {
            textContent += op.insert; // 处理纯文本
          } else if (op.insert.image) {
            textContent += '[图片]'; // 替换图片为 *
          }
        }
      });
     if(textContent==''|| textContent.length<5){
       alert('内容不能为空或少于5个字')
       return;
     }
      const params = {
        ct: 'dongtai',
        ac: "add",
        sign: this.textToHash,
        t: this.t,
        uid: this.uid,
        content: textContent,
        subject_id: this.dongtai.gid,
        gid: this.dongtai.subject_id,
        imgs: this.selectedarray
      };
      const response = await this.$axios.get('api/app/v3', { params });
      this.$router.back();
    },
    handleEditorChange(delta, oldDelta, source) {
      const content = this.editor.root.innerHTML;
      if (!content.includes('topic-name')) {
      }
      this.dongtai.title = delta.ops.length
      
    },
    async youxiTopicList(e) {
      const params = {
        ct: 'gamenav',
        ac: e,
        sign: this.textToHash,
        t: this.t,
        uid: this.uid,
        keyword: ''
      };
      const response = await this.$axios.get('api/app/v3', { params });
      this.topics = response.data.data.map(topic => {
        return { ...topic, type: e === 'segame' ? 'game' : 'subject' };
      });
      this.showTopicList = !this.showTopicList;
    },
    removeImage(index) {
      this.selectedarray.splice(index, 1);
    },
    goBack() {
      this.$router.go(-1);
    },
    getCookie(name) {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) return parts.pop().split(';').shift();
      return '';
    },
    triggerFileInput() {
      document.getElementById('fileInput').click();
    },
async handleFileChange(event) {
    const files = event.target.files;
    let newArray = [];
    if (files.length > 0) {
        for (const file of Array.from(files)) {
            if (file.type.startsWith('image/')) {
                const formData = new FormData();
                formData.append('image', file);

                const response = await this.$axios.post('/?ct=app&ac=upload', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' },
                });
                newArray.push(response.data);
            }
        }
        this.selectedarray = [...this.selectedarray, ...newArray];
    }
},
   getImageStyle(count) {
      let width, height;
      if (count === 1) {
        width = '270px';
        height = '152px';
      } else if (count === 2) {
        width = '135px';
        height = '83px';
      } else {
        width = '100px';
        height = '100px';
      }
      return { width, height };
    },
getImageClass(index, count) {
  const rowIndex = Math.floor(index / 3);
  const colIndex = index % 3;

  let className = '';
  if (count === 2) {
       if (index === 0) {
      return 'rounded-top-left';
    }
    if (index === 1) {
      return 'rounded-top-right';
    }
  } else if (count === 9) {
    if (rowIndex === 0) { // 第一行
      if (colIndex === 0) {
        className = 'rounded-top-left';
      } else if (colIndex === 2) {
        className = 'rounded-top-right';
      }
    } else if (rowIndex === 2) {
      if (colIndex === 0) {
        className = 'rounded-bottom-left';
      } else if (colIndex === 2) {
        className = 'rounded-bottom-right';
      }
    }
  } else if (count >= 7) {
    if (rowIndex === 1) { // 第二行
      // 第二行的图片圆角保持不变
      if (colIndex === 0) {
        // className = 'rounded-left';
      } else if (colIndex === 2) {
        // className = 'rounded-right';
      } else {
        className = '';
      }
    } else if (rowIndex === 0) {
      if (colIndex === 0) {
        className = 'rounded-top-left';
      } else if (colIndex === 2) {
        className = 'rounded-top-right';
      }
    } else if (rowIndex === Math.floor((count - 1) / 3)) {
      if (colIndex === 0) {
        className = 'rounded-bottom-left';
      } else if (colIndex === 2) {
        className = 'rounded-bottom-right';
      }
    } else {
      className = colIndex === 0 ? 'rounded-left' : colIndex === 2 ? 'rounded-right' : '';
    }
  } else if (count === 1) {
    className = 'rounded';
  } else {
    if (rowIndex === 0 && colIndex === 0) {
      className = 'rounded-top-left';
    } else if (rowIndex === 0 && colIndex === 2) {
      className = 'rounded-top-right';
    } else if (rowIndex === Math.floor((count - 1) / 3) && colIndex === 0) {
      className = 'rounded-bottom-left';
    } else if (rowIndex === Math.floor((count - 1) / 3) && colIndex === 2) {
      className = 'rounded-bottom-right';
    } else {
      className = colIndex === 0 ? 'rounded-left' : colIndex === 2 ? 'rounded-right' : '';
    }
  }

  return className;
},
    insertTopic(topic) {
      if (topic.icon !== undefined) {
        if (this.dongtai.subject_id === '') {
          this.dongtai.subject_id = topic.id;
        } else {
          this.dongtai.subject_id += ',' + topic.id;
        }
      } else {
        if (this.dongtai.gid === '') {
          this.dongtai.gid = topic.id;
        } else {
          this.dongtai.gid += ',' + topic.id;
        }
      }

      this.$nextTick(() => {
        this.editor.focus();
        const range = this.editor.getSelection();
        if (range) {
          let content = topic.name;
          let color = '#000000';
          if (topic.type == 'game') {
            color = '#3D9399FF';
            this.editor.insertEmbed(range.index, 'image', 'https://www.77.top/static/gametag.png', Quill.sources.USER);
            this.editor.insertText(range.index + 1, content, 'color', color, Quill.sources.USER);
          } else if (topic.type == 'subject') {
            color = '#E57617FF';
            content = `# ${topic.name}`;
            this.editor.insertText(range.index, content, 'color', color, Quill.sources.USER);
          }

          this.editor.insertText((range.index + 1) + content.length, ' ', 'color', '#000000', Quill.sources.USER);
          const editorContainer = this.editor.root;
          const imageElements = editorContainer.querySelectorAll('img');
          if (imageElements.length > 0) {
            const lastImage = imageElements[imageElements.length - 1];
            lastImage.style.width = '20px';
            lastImage.style.height = '20px';
            lastImage.style.transform = 'translateY(6px)';
          }
          const length = this.editor.getLength();
          this.editor.setSelection(length, length, Quill.sources.SILENT);
          this.showTopicList = false;
        } else {
        }
      });
    },
  }
}
</script>

<style scoped>

.topic-list {
  position: absolute;
  background: #EDEEF0;
  border: .0625rem solid #ddd;
  border-radius:.5rem;
  box-shadow: 0 .125rem .625rem rgba(0, 0, 0, 0.1);
  max-height: 18rem;
  overflow-y: auto;
  width:276px;
  z-index: 1000;
  top: 35px;
}

.topic-item {
  padding: 10px;
  cursor: pointer;
}

.topic-item:hover {
  background-color: #f0f0f0;
}

.topic-color-game {
}

.topic-color-subject {
  width: 18.75rem;
}

.tupians {
  display: flex;
  flex-wrap: wrap;
  margin-top: .75rem;
}
.fabuquanzi{
width: 21.375rem;
height: 2.5rem;
margin:0 auto;
line-height: 2.5rem;
background: linear-gradient( 91deg, #FDA509 0%, #F27810 100%);
border-radius:3.25rem;
color: #FFFFFFFF;
text-align: center;
font-size: 1rem;
}
.image-gallery {
  display: flex;
  flex-wrap: wrap;
  
  margin: .5rem 1.25rem .5rem 1.25rem;
  gap: 1px;
  justify-content: left; 
}

.image-gallery img {
  object-fit: cover; /* 保持图片比例 */
}

.rounded {
  border-radius: 8px;
}

.rounded-left {
  border-top-left-radius: 8px;
  border-bottom-left-radius: 8px;
}

.rounded-right {
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
}

.rounded-top-left {
  border-top-left-radius: 8px;
}

.rounded-top-right {
  border-top-right-radius: 8px;
}

.rounded-bottom-left {
  border-bottom-left-radius: 8px;
}

.rounded-bottom-right {
  border-bottom-right-radius: 8px;
}
</style>